<?php


namespace Home\Model;

use Think\Model\RelationModel;
use Think\Page;

class MeetingsModel extends RelationModel
{
    protected $ITManager = 1789;   //管理员

    protected $_link = [
        'user' => [
            'mapping_type' => self::BELONGS_TO,   //关联类型
            'foreign_key' => 'user_id',    //外键
            'class_name' => 'User',      //要关联的模型类名
            'mapping_fields' => [     //关联的映射名称，用于获取数据用
                'nickname' => 'author_name',  //姓名
                'face' => 'author_avatar'    //头像
            ]
        ],
        'host_detail' => [
            'mapping_type' => self::BELONGS_TO,   //关联类型
            'foreign_key' => 'host',    //外键
            'class_name' => 'User',      //要关联的模型类名
            'mapping_fields' => [     //关联的映射名称，用于获取数据用
                'nickname' => 'author_name',  //姓名
                'face' => 'author_avatar'    //头像
            ]
        ],
        'recorder_detail' => [
            'mapping_type' => self::BELONGS_TO,   //关联类型
            'foreign_key' => 'recorder',    //外键
            'class_name' => 'User',      //要关联的模型类名
            'mapping_fields' => [     //关联的映射名称，用于获取数据用
                'nickname' => 'author_name',  //姓名
                'face' => 'author_avatar'    //头像
            ]
        ]
    ];

    //当前登录是否是创建者
    public function isAuthor($userId)
    {
        return session('user')['id'] == $userId;
    }

    /**
     * 查询会议室的预约情况
     * @param $meetingData:会议室信息
     * @param $now:当前时间
     * @return $meetingData:会议室信息且包含预约信息
     */
    public function inquireReservation($meetingData,$now,$id=0)
    {
        //获取预约信息
        foreach ($meetingData as $key => &$data) {
            $map = "find_in_set({$data['id']},`meeting_room_id`) and (unix_timestamp(start_time) >= unix_timestamp('{$now}') or unix_timestamp(end_time) >= unix_timestamp('{$now}')) and status=0 and id<>{$id}";
            $data['details'] = $this->relation(['user'])->field(['id, title, user_id, start_time, end_time'])->where($map)->order("start_time asc")->select();

            //处理时间格式
            foreach ($data['details'] as &$detail) {
                $detail['start_time'] = $this->changeTime($detail['start_time'],3);
                $detail['end_time'] = $this->changeTime($detail['end_time'],2);
            }
        }

        return $meetingData;
    }

    //处理时间格式
    public function changeTime($time,$type)
    {
        if ($type == 1)  //转换为'Y-m-d'
        {
            return date('Y-m-d', strtotime($time));
        }
        if ($type == 2)   //转换为'H:i'
        {
            return date('H:i', strtotime($time));
        }
        if ($type == 3)   //转换为'Y-m-d H:i'
        {
            return date('Y-m-d H:i', strtotime($time));
        }
        if ($type == 4)   //转换为'Y年m月d日'
        {
            return date('Y年m月d日', strtotime($time));
        }
        if ($type == 5)   //转换为'yyyymmddhhii'
        {
            return date('YmdHi', strtotime($time));
        }
    }

    //改变状态
    public function changeStatus($start, $end, $now)
    {
        if (strtotime($start) > strtotime($now))
        {
            return 0; //未开始
        }
        if (strtotime($start) < strtotime($now) && strtotime($end) > strtotime($now))
        {
            return 1; //进行中
        }
        if (strtotime($end) < strtotime($now))
        {
            return 2;  //已结束
        }
    }

    //查询我的会议（我申请的or我参加的or我能看到的所有会议）
    public function inquireMyMeetings($user_id,$now,$type,$map)
    {
        $data = [];
        $page = [];
        if ($type == 'create')
        {
            $count = $this->where($map)->where("user_id={$user_id}")->count();
            $page = $this->getPage($count,6);
            $data = $this->relation(['user'])->where($map)->where("user_id={$user_id}")->limit($page->firstRow . ',' . $page->listRows)->order("end_time DESC")->select();
        }
        if ($type == 'participate')
        {
            $count = $this->where($map)->where("find_in_set({$user_id},participants)")->count();
            $page = $this->getPage($count,6);
            $data = $this->relation(['user'])->where($map)->where("find_in_set({$user_id},participants)")
                ->limit($page->firstRow . ',' . $page->listRows)->order("end_time DESC")->select();
        }
        if ($type == 'all')
        {
            $meetings = $this->relation(['user'])->field(['atop_meetings.*','group_concat(atop_meeting_rooms.auth_group)'=>'auth_group'])
                ->join("atop_meeting_rooms ON find_in_set(atop_meeting_rooms.id,atop_meetings.meeting_room_id)")
                ->where($map)
                ->group('atop_meetings.id')->order("end_time DESC")
                ->select();
            foreach ($meetings as &$meeting)
            {
                if ($this->isShow($meeting['id']))
                {
                    $data[] = $meeting;
                }
            }
            $count = count($data);
            $page = $this->getPage($count,6);
            $data = array_slice($data, $page->firstRow,$page->listRows); //数组分页
        }

        foreach ($data as &$item)
        {
            $item['rooms'] = M('MeetingRooms')->field('name')->where("id in ({$item['meeting_room_id']})")->select();
            $item['time_status'] = $this->changeStatus($item['start_time'],$item['end_time'],$now);
            $item['year'] = $this->changeTime($item['start_time'],1);
            $item['start'] = $this->changeTime($item['start_time'],2);
            $item['end'] = $this->changeTime($item['end_time'],2);
        }

        return [$data,$page,$count];
    }

    //数据分页
    public function getPage($count,$num)
    {
        $page = new Page($count, $num);
        $page->setConfig('prev', '<span aria-hidden="true">上一页</span>');
        $page->setConfig('next', '<span aria-hidden="true">下一页</span>');
        $page->setConfig('first', '<span aria-hidden="true">首页</span>');
        $page->setConfig('last', '<span aria-hidden="true">尾页</span>');

        if (C('PAGE_STATUS_INFO')) {
            $page->setConfig('theme', '<li><a href="javascript:void(0);">当前%NOW_PAGE%/%TOTAL_PAGE%</a></li>  %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
        }

        return $page;
    }

    //判断会议时间是否冲突，return 0 不冲突，1冲突
    public function inquireAllTime($rooms, $start, $end, $id=0)
    {
        for ($i = 0; $i<count($rooms); $i++) {
            $items = M('Meetings')->field(['start_time, end_time'])->where("find_in_set($rooms[$i],`meeting_room_id`) and id<>{$id} and status=0")->select();
            $data[$i] = $items;
            foreach ($items as &$item) {
                if ((strtotime($start) >= strtotime($item['end_time'])) || (strtotime($end) <= strtotime($item['start_time']))) {
                    $type = 0;
                } else {
                    $type = 1;
                    break;   //跳出foreach循环
                }
            }
            if ($type == 1 ) {
                break; //跳出for循环
            }

        }

        return [$type,$data];
    }

    //判断权限（只有特殊授权及IT管理员以及参会人员、申请人能够看到）
    public function isShow($id,$type = 0)
    {
        $meeting = $this->field(['atop_meetings.participants','atop_meetings.user_id','group_concat(atop_meeting_rooms.auth_group)'=>'auth_group'])
            ->join('atop_meeting_rooms ON find_in_set(atop_meeting_rooms.id,atop_meetings.meeting_room_id)')
            ->group('atop_meetings.id')->where("atop_meetings.id = {$id}")->find();
        $post = explode(',', session('user')['post']);
        $auth_group = explode(',' ,$meeting['auth_group']);
        $user_id = session('user')['id'];
        if ($type == 0)
        {
            if (in_array($user_id,explode(',',$meeting['participants'])) || array_intersect($post,$auth_group) || in_array($this->ITManager,$post) || $user_id == $meeting['user_id'])
            {
                return true;
            } else {
                return false;
            }
        } else { //除去IT管理员的条件
            if (in_array($user_id,explode(',',$meeting['participants'])) || array_intersect($post,$auth_group) || $user_id == $meeting['user_id'])
            {
                return true;
            } else {
                return false;
            }
        }
    }

    //是否是IT管理员
    public function isManager()
    {
        $post = explode(',', session('user')['post']);
        return in_array($this->ITManager,$post);
    }

}